package com.psedu.base.service.impl;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.psedu.base.constant.CacheConstant;
import com.psedu.base.constant.Constants;
import com.psedu.base.domain.Apply;
import com.psedu.base.domain.SignLaunch;
import com.psedu.base.domain.vo.*;
import com.psedu.base.mapper.ApplyMapper;
import com.psedu.base.mapper.SemesterDeptMapper;
import com.psedu.base.mapper.SignLaunchMapper;
import com.psedu.common.core.constant.SecurityConstants;
import com.psedu.common.core.domain.R;
import com.psedu.common.core.utils.BeanCopyUtils;
import com.psedu.common.redis.service.RedisService;
import com.psedu.common.security.utils.SecurityUtils;
import com.psedu.system.api.RemoteDeptService;
import com.psedu.system.api.domain.vo.SysSimpleDeptVo;
import com.psedu.system.api.model.LoginUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.psedu.base.mapper.CourseMapper;
import com.psedu.base.domain.Course;
import com.psedu.base.service.ICourseService;

/**
 * 课程Service业务层处理
 * 
 * @author mingyue
 * @date 2022-02-10
 */
@Service
public class CourseServiceImpl implements ICourseService 
{
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private ApplyMapper applyMapper;
    @Autowired
    private RemoteDeptService remoteDeptService;
    @Autowired
    private SemesterDeptMapper semesterDeptMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private SignLaunchMapper signLaunchMapper;

    /**
     * 查询课程
     * 
     * @param courseId 课程主键
     * @return 课程
     */
    @Override
    public CourseSignLaunchVo selectCourseByCourseId(Long courseId)
    {
        List<SignLaunch> signLaunches = signLaunchMapper.selectList(
                new LambdaQueryWrapper<SignLaunch>()
                        .eq(SignLaunch::getCourseId, courseId)
        );
        CourseSignLaunchVo courseSignLaunchVo = new CourseSignLaunchVo();
        if(CollectionUtil.isNotEmpty(signLaunches)) {
            courseSignLaunchVo.setSignLaunch(signLaunches.get(0));
        }
        Course course = courseMapper.selectCourseByCourseId(courseId);
        BeanUtils.copyProperties(course, courseSignLaunchVo);
        return courseSignLaunchVo;
    }

    /**
     * 查询课程列表
     * 
     * @param course 课程
     * @return 课程
     */
    @Override
    public List<CourseVo> selectCourseList(Course course)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 分党校只能看本部门的
        Long deptId = loginUser.getDeptId();
        if(deptId == null) {
            return null;
        }
        List<Course> list = null;
        // 管理员能看所有
        if(Constants.ADMIN_DEPT_ID == deptId) {
            list = courseMapper.selectCourseList(course);
        } else {
            list = courseMapper.selectCourseForDept(course, deptId);
        }
        System.out.println(remoteDeptService.getDeptNameByDeptId(Arrays.asList(200L, 201L), SecurityConstants.INNER));
        List<Long> needDeptIds = list.stream().filter(courseItem -> courseItem.getDeptId() != 0).map(Course::getDeptId).collect(Collectors.toList());
        // 对应的部门转换为Map
        Map<Long, String> deptMap = new HashMap<>();
        if(needDeptIds != null && needDeptIds.size() != 0) {
            R<List<SysSimpleDeptVo>> deptNameByDeptIdRes = remoteDeptService.getDeptNameByDeptId(needDeptIds, SecurityConstants.INNER);
            // system成功
            if(deptNameByDeptIdRes.getCode() == com.psedu.common.core.constant.Constants.SUCCESS) {
                List<SysSimpleDeptVo> sysSimpleDeptVos = deptNameByDeptIdRes.getData();
                deptMap = sysSimpleDeptVos.stream().collect(Collectors.toMap(SysSimpleDeptVo::getDeptId, SysSimpleDeptVo::getDeptName));
            }
        }
        Map<Long, String> finalDeptMap = deptMap;
        List<CourseVo> courseVos = list.stream().map(courseItem -> {
            CourseVo courseVo = new CourseVo();
            BeanUtils.copyProperties(courseItem, courseVo);
            // 不针对部门，范围：合班
            if (courseItem.getDeptId() == 0) {
                courseVo.setDeptScope(courseItem.getMergeClassId() + "合班");
            } else {
                courseVo.setDeptScope(finalDeptMap.get(courseItem.getDeptId()));
            }
            return courseVo;
        }).collect(Collectors.toList());
        return courseVos;
    }

    /**
     * 新增课程
     * 
     * @param course 课程
     * @return 结果
     */
    @Override
    public int insertCourse(CourseSignLaunchVo course)
    {
        // 实现的是针对学院的
        if(course.getRealizeCourseId() != 0) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            // 没登录
            if(loginUser == null) {
                return 0;
            }
            course.setDeptId(loginUser.getDeptId());
        }
        courseMapper.insert(course);
        SignLaunch signLaunch = course.getSignLaunch();
        if(signLaunch.getStartTime() != null) {
            signLaunch.setSignTitle("第一轮签到");
            signLaunch.setCourseId(course.getCourseId());
            signLaunchMapper.insert(signLaunch);
        }
        return 1;
    }

    /**
     * 修改课程
     * 
     * @param course 课程
     * @return 结果
     */
    @Override
    public int updateCourse(CourseSignLaunchVo course)
    {
        SignLaunch signLaunch = course.getSignLaunch();
        signLaunchMapper.delete(
                new LambdaQueryWrapper<SignLaunch>()
                        .eq(SignLaunch::getCourseId, course.getCourseId())
        );
        if(signLaunch.getStartTime() != null) {
            signLaunch.setSignTitle("第一轮签到");
            signLaunch.setCourseId(course.getCourseId());
            SignLaunch signLaunch1 = new SignLaunch();
            BeanCopyUtils.copy(signLaunch, signLaunch1);
            signLaunchMapper.insert(signLaunch1);
        }
        return courseMapper.updateById(course);
    }

    /**
     * 批量删除课程
     * 
     * @param courseIds 需要删除的课程主键
     * @return 结果
     */
    @Override
    public int deleteCourseByCourseIds(Long[] courseIds)
    {
        return courseMapper.deleteCourseByCourseIds(courseIds);
    }

    /**
     * 删除课程信息
     * 
     * @param courseId 课程主键
     * @return 结果
     */
    @Override
    public int deleteCourseByCourseId(Long courseId)
    {
        return courseMapper.deleteCourseByCourseId(courseId);
    }

    /**
     * 获取用户的所有课程
     * @param applyId 申请ID
     * @return 用户的所有课程列表
     */
    // TODO
    @Override
    public List<UserCourseVo> getUserCourse(Long applyId) {
        // 本合班的 (没规定部门的 OR 本部门)
        Apply apply = applyMapper.selectById(applyId);
        List<CourseSignLaunchVo> courseList =  courseMapper.selectDeptCourse(
                                                        apply.getDeptId(),
                                                        apply.getSemeId()
                                                );

        return null;
    }

    @Override
    public SemeCourseVo getDeptCourseInfo(Long semeId, Long deptId) {
        List<CourseSignLaunchVo> courseList =  courseMapper.selectDeptCourse(deptId, semeId);
        List<CourseSimpleVo> courseSimpleVoList = courseList.stream().map(course -> {
            CourseSimpleVo courseSimpleVo = new CourseSimpleVo();
            SignLaunch signLaunch = course.getSignLaunch();
            BeanUtils.copyProperties(course, courseSimpleVo);
            if(signLaunch != null) {
                courseSimpleVo.setSignLaunchId(signLaunch.getSignLaunchId());
                courseSimpleVo.setSignTitle(signLaunch.getSignTitle());
                courseSimpleVo.setSignStartTime(signLaunch.getStartTime());
                courseSimpleVo.setSignEndTime(signLaunch.getEndTime());
            }
            Long courseId = courseSimpleVo.getCourseId();
            Object liveCourseStatus = redisService.getCacheMapValue(CacheConstant.LIVE_COURSE_KEY, "" + courseId);
            if(liveCourseStatus != null && "1".equals("" +liveCourseStatus)) {
                courseSimpleVo.setLiveUrl("course" + courseId);
            }
            return courseSimpleVo;
        }).collect(Collectors.toList());
        SemeCourseVo semeCourseVo = new SemeCourseVo();
        semeCourseVo.setCourseSimpleVoList(courseSimpleVoList);
        semeCourseVo.setDeptId(deptId);
        semeCourseVo.setSemeId(semeId);
        return semeCourseVo;
    }

    @Override
    public boolean liveStatus(Long courseId, Integer liveStatus) {
        redisService.setCacheMapValue(CacheConstant.LIVE_COURSE_KEY, "" +courseId, liveStatus);
        return true;
    }
}
